<template>
  <div class="app-container">
    <div class="header">
      <el-page-header @back="goBack" :content="pathInfo.name + ' - 节点管理'" />
    </div>

    <div class="filter-container">
      <el-button type="primary" @click="handleAdd">添加节点</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
      row-key="id"
    >
      <el-table-column
        prop="nodeId"
        label="节点ID"
        min-width="200">
      </el-table-column>
      <el-table-column
        prop="sequence"
        label="序号"
        width="80">
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="handleDialogClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="知识点" prop="nodeId">
          <el-select
            v-model="form.nodeId"
            filterable
            placeholder="请选择知识点"
            style="width: 100%">
            <el-option
              v-for="item in nodeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="序号" prop="sequence">
          <el-input-number
            v-model="form.sequence"
            :min="0"
            :max="999"
            style="width: 100%"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { http } from '@/api'

export default {
  name: 'PathNode',
  data() {
    return {
      loading: false,
      pathInfo: {
        id: null,
        name: '',
        domain: ''
      },
      tableData: [],
      nodeOptions: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        pathId: null,
        nodeId: null,
        sequence: 0
      },
      rules: {
        nodeId: [
          { required: true, message: '请选择知识点', trigger: 'change' }
        ],
        sequence: [
          { required: true, message: '请输入序号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const pathId = this.$route.params.pathId
    if (pathId) {
      this.pathInfo.id = pathId
      this.form.pathId = pathId
      this.getList()
      this.getNodeOptions()
    } else {
      this.$message.error('未找到路径信息')
      this.goBack()
    }
  },
  methods: {
    getNodeTypeName(type) {
      const types = {
        1: '概念',
        2: '定理',
        3: '公式',
        4: '规则',
        5: '设备',
        6: '技术'
      }
      return types[type] || '-'
    },
    async getList() {
      this.loading = true
      try {
        const res = await http.learningPath.getPathNodes(this.pathInfo.id)
        this.tableData = res.data
      } catch (error) {
        console.error(error)
        this.$message.error('获取节点列表失败')
      }
      this.loading = false
    },
    async getNodeOptions() {
      try {
        const res = await http.knowledgeNode.page({ current: 1, size: 99999})
        this.nodeOptions = res.data.records
      } catch (error) {
        console.error(error)
        this.$message.error('获取知识点列表失败')
      }
    },
    handleAdd() {
      this.dialogTitle = '添加节点'
      this.form = {
        id: null,
        pathId: this.pathInfo.id,
        nodeId: null,
        sequence: 0
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑节点'
      this.form = { ...row }
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确认删除该节点吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await http.learningPath.deletePathNode(row.id)
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          console.error(error)
          this.$message.error('删除失败')
        }
      })
    },
    handleDialogClose() {
      this.$refs.form.resetFields()
      this.dialogVisible = false
    },
    async handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            if (this.form.id) {
              await http.learningPath.updatePathNode(this.form)
              this.$message.success('更新成功')
            } else {
              await http.learningPath.addPathNode(this.form)
              this.$message.success('添加成功')
            }
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error(error)
            this.$message.error(this.form.id ? '更新失败' : '添加失败')
          }
        }
      })
    },
    goBack() {
      this.$router.push({ name: 'LearningPath' })
    }
  },
  beforeDestroy() {
    // 清除localStorage中的路径信息
    localStorage.removeItem('currentPath')
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}
.filter-container {
  margin-bottom: 20px;
}
</style>
